/**
 * @(#)HttpPostCaller.java 2016年11月3日
 * Copyright(C) 2016 ZHEXIN IT CO.,LTD. All rights reserved.
 */
package org.jsbd.boss.httpclient;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.jsbd.boss.exception.ParamErrorException;
import org.jsbd.boss.exception.ParamNullException;
import org.jsbd.boss.httpclient.vo.BaseRequest;
import org.jsbd.boss.httpclient.vo.Request;
import org.jsbd.boss.httpclient.vo.Response;
import org.jsbd.boss.httpclient.vo.XmlOrJsonRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * TODO 请加入本类的说明
 * 
 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
 * @version 1.0.0
 */
public class HttpPostCaller extends HttpCaller {
	public static final Logger LOGGER = LoggerFactory.getLogger(HttpPostCaller.class);
	private BaseRequest request;
	private HttpPost httpPost;

	/**
	 * create an instance of HttpPostCaller
	 * 
	 * @param request
	 */
	public HttpPostCaller(BaseRequest request) {
		super(request);
		this.request = request;
	}

	/**
	 * 
	 * doPost:doPost
	 * 
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @return
	 * @throws IOException
	 */
	public Response doPost() {
		if (request == null) {
			throw new ParamNullException("请求参数为空!");
		}
		String url = request.getUrl();
		if (StringUtils.isBlank(url)) {
			throw new ParamNullException("请求地址为空!");
		}
		Response result = new Response();
		CloseableHttpResponse response = null;
		try {
			httpPost = new HttpPost(url);
			httpPost.setConfig(buildRequestConfig());
			builderPostFormEnrity();
			builderPostHeaders();
			response = httpclient.execute(httpPost);
			StatusLine statusLine = response.getStatusLine();
			int statusCode = statusLine.getStatusCode();
			result.setStatus(statusCode);
			if (statusCode == HttpURLConnection.HTTP_OK) {
				result.setSuccess(true);
				result.setHeaders(response.getAllHeaders());
			} else {
				result.setSuccess(false);
				LOGGER.warn("http response status code is not 200. status line: {}" + statusLine);
			}
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				String res = EntityUtils.toString(entity);
				result.setData(res);
			} else {
				LOGGER.warn("Response contains no content");
			}
		} catch (Exception e) {
			result.setSuccess(false);
			LOGGER.error("http call error", e);
		} finally {
			if (httpPost != null) {
				httpPost.abort();
			}
			try {
				if (response != null) {
					response.close();
				}
			} catch (Exception e) {
				LOGGER.error("", e);
			}
			try {
				if (httpclient != null) {
					httpclient.close();
				}
			} catch (Exception e) {
				LOGGER.error("链接关闭失败", e);
			}
		}

		return result;
	}

	public Response doPostXmlOrJSON() {
		if (request instanceof XmlOrJsonRequest) {
			XmlOrJsonRequest xmlOrJsonRequest = (XmlOrJsonRequest) request;
			if (xmlOrJsonRequest == null) {
				throw new ParamNullException("请求参数为空!");
			}
			String url = xmlOrJsonRequest.getUrl();
			if (StringUtils.isBlank(url)) {
				throw new ParamNullException("请求地址为空!");
			}
			String data = xmlOrJsonRequest.getData();
			if (StringUtils.isBlank(data)) {
				throw new ParamNullException("请求xml参数为空!");
			}
			Response result = new Response();
			CloseableHttpResponse response = null;
			try {
				httpPost = new HttpPost(url);
				httpPost.setConfig(buildRequestConfig());
				String key = xmlOrJsonRequest.getKey();
				if (StringUtils.isNotBlank(key)) {
					Request request = new Request();
					Map<String, String> params = new HashMap<String, String>();
					params.put(key, data);
					request.setParams(params);
					builderPostFormEnrity();
				} else {
					StringEntity requestEntity = new StringEntity(data, Consts.UTF_8);
					httpPost.setEntity(requestEntity);
				}
				builderPostHeaders();
				response = httpclient.execute(httpPost);
				StatusLine statusLine = response.getStatusLine();
				int statusCode = statusLine.getStatusCode();
				result.setStatus(statusCode);
				if (statusCode == HttpURLConnection.HTTP_OK) {
					result.setSuccess(true);
					result.setHeaders(response.getAllHeaders());
				} else {
					result.setSuccess(false);
					LOGGER.warn("http response status code is not 200. status line: {}" + statusLine);
				}
				HttpEntity entity = response.getEntity();
				if (entity != null) {
					String res = EntityUtils.toString(entity);
					result.setData(res);
				} else {
					LOGGER.warn("Response contains no content");
				}
			} catch (Exception e) {
				result.setSuccess(false);
				LOGGER.error("http call error", e);
			} finally {
				if (httpPost != null) {
					httpPost.abort();
				}
				try {
					if (response != null) {
						response.close();
					}
				} catch (Exception e) {
					LOGGER.error("", e);
				}
				try {
					if (httpclient != null) {
						httpclient.close();
					}
				} catch (Exception e) {
					LOGGER.error("链接关闭失败", e);
				}
			}
			return result;
		} else {
			throw new ParamErrorException("请求参数类型不对!");
		}

	}

	/**
	 * 
	 * builderPostFormEnrity:构建post请求参数
	 * 
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	private void builderPostFormEnrity() throws UnsupportedEncodingException {
		Map<String, String> params = request.getParams();
		if (params != null && !params.isEmpty()) {
			List<NameValuePair> nvps = new ArrayList<NameValuePair>();
			String[] keys = params.keySet().toArray(new String[0]);
			for (String key : keys) {
				String value = params.get(key);
				if (StringUtils.isNotBlank(value)) {
					nvps.add(new BasicNameValuePair(key, params.get(key)));
				}
			}
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
		}
	}

	/**
	 * 
	 * builderPostHeaders:访问头信息
	 * 
	 * @author <a href="mailto:xupengcheng@zhexinit.com" >徐鹏程</a>
	 */
	private void builderPostHeaders() {
		Map<String, String> headers = request.getHeaders();
		if (headers != null && !headers.isEmpty()) {
			String[] keys = headers.keySet().toArray(new String[0]);
			for (String key : keys) {
				String value = headers.get(key);
				if (StringUtils.isNotBlank(value)) {
					httpPost.addHeader(new BasicHeader(key, headers.get(key)));
				}
			}
		}
	}
}
